package org.freez4.spring.resource;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * 注入 {@link ResourceLoader} 对象示例
 *
 * @author 阿坤同学
 * @date 2024/1/19 10:26 AM
 * @see ResourceLoader
 * @see Resource
 * @see Value
 * @see AnnotationConfigApplicationContext
 */
public class InjectingResourceLoaderDemo implements ResourceLoaderAware, InitializingBean {

    public static final Logger logger = Logger.getLogger(InjectingResourceLoaderDemo.class.getName());

    private ResourceLoader resourceLoader; // 方法一

    private ResourceLoader autowiredResourceLoader; // 方法二

    private AbstractApplicationContext applicationContext; // 方法三

    public InjectingResourceLoaderDemo(ResourceLoader autowiredResourceLoader, AbstractApplicationContext applicationContext) {
        this.autowiredResourceLoader = autowiredResourceLoader;
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        logger.log(Level.INFO, () -> "resourceLoader == autowiredResourceLoader : " + (resourceLoader == autowiredResourceLoader));
        logger.log(Level.INFO, () -> "resourceLoader == applicationContext : " + (resourceLoader == applicationContext));
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        // 注册当前类作为 Configuration Class
        context.register(InjectingResourceLoaderDemo.class);
        // 启动 Spring 应用上下文
        context.refresh();
        // 关闭 Spring 应用上下文
        context.close();
    }
}